from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from tools.jwt_decode import login
from .models import *
import xlrd2
from email.header import Header
from email.mime.text import MIMEText
import smtplib
# Create your views here.
# 菜单查询，增加
class MenuAPIView(APIView):
    @login
    def get(self,request):
        """
        menu_name
        menu_way
        menu_logo
        menu_level
        menu_sort

        """

        menu_father = MenuModel.objects.filter(menu_level=None)
        temp_father = []
        father = []
        for i in menu_father:
            father.append({
                'id': str(i.id),
                'menu_name': i.menu_name,
                'menu_way': i.menu_way,
                'menu_logo': i.menu_logo,
                'menu_level': i.menu_level_id,
                'menu_sort': i.menu_sort
            })
        child = []
        for i in menu_father.all():
            menu_childs = MenuModel.objects.filter(menu_level_id=i.id)
            for j in menu_childs:
                child.append({
                    'id': str(j.id),
                    'menu_name': j.menu_name,
                    'menu_way': j.menu_way,
                    'menu_logo': j.menu_logo,
                    'menu_level': j.menu_level_id,
                    'menu_sort': j.menu_sort
                })

        # 先找到子级数据
        for i in menu_father:
            menu_child = MenuModel.objects.filter(menu_level_id=i.id)
            temp_child = []
            for j in menu_child:
                temp_child.append({
                    'id':str(j.id),
                    'menu_name':j.menu_name,
                    'menu_way':j.menu_way,
                    'menu_logo':j.menu_logo,
                    'menu_level':j.menu_level_id,
                    'menu_sort':j.menu_sort
                })
            temp_father.append({
                'id':str(i.id),
                'menu_name':i.menu_name,
                'menu_way':i.menu_way,
                'menu_logo':i.menu_logo,
                'menu_level': i.menu_level_id,
                'menu_child_list':temp_child,
                'menu_sort':i.menu_sort
            })

        return Response({
            'code':200,
            'msg':'获取菜单成功',
            'menu':temp_father,
            'father':father,
            'child':child
        })

    @login
    def post(self,request):
        """
            menu_name
            menu_way
            menu_logo
            menu_level
            menu_sort

        """
        uid = request.uid
        user = UserModel.objects.get(id=uid)
        if user.role_id_id != 2:
            return Response({
                'code': 400,
                'msg': '抱歉，您没有权限'
            })
        menu_name = request.data.get('menu_name')
        menu_way = request.data.get('menu_way')
        menu_logo = request.data.get('menu_logo')
        menu_level = request.data.get('menu_level')
        menu_sort = request.data.get('menu_sort')
        if not all([menu_name,menu_way,menu_logo,menu_sort]):
            return Response({
                'code':400,
                'msg':'数据输入不完整'
            })
        name = MenuModel.objects.filter(menu_name=menu_name)
        if not name:
            MenuModel.objects.create(menu_name=menu_name,menu_way=menu_way,menu_logo=menu_logo,menu_level_id=menu_level,menu_sort=menu_sort)
        else:
            return Response({
                'code':400,
                'msg':'已有此目录'
            })
        return Response({
            'code':200,
            'msg':'菜单目录存入成功'
        })

# 菜单修改，删除
class MenuView(APIView):
    # 查看单条菜单
    @login
    def get(self,request,id):
        uid = request.uid
        user = UserModel.objects.get(id=uid)
        if user.role_id_id != 2:
            return Response({
                'code': 400,
                'msg': '抱歉，您没有权限'
            })
        menu_one = MenuModel.objects.get(id=id)
        return Response({
            'code':200,
            'msg':'获取单个菜单成功',
            'data':{
                'id': str(menu_one.id),
                'menu_name': menu_one.menu_name,
                'menu_way': menu_one.menu_way,
                'menu_logo': menu_one.menu_logo,
                'menu_level': menu_one.menu_level_id,
                'menu_sort': menu_one.menu_sort
            }
        })

    @login
    def delete(self,request,id):
        uid = request.uid
        user = UserModel.objects.get(id=uid)
        if user.role_id_id != 2:
            return Response({
                'code': 400,
                'msg': '抱歉，您没有权限'
            })
        MenuModel.objects.get(id=id).delete()
        return Response({
            'code':200,
            'msg':'删除目录成功'
        })

    @login
    def put(self,request,id):
        uid = request.uid
        user = UserModel.objects.get(id=uid)
        if user.role_id_id != 2:
            return Response({
                'code': 400,
                'msg': '抱歉，您没有权限'
            })
        menu_name = request.data.get('menu_name')
        menu_way = request.data.get('menu_way')
        menu_logo = request.data.get('menu_logo')
        menu_level = request.data.get('menu_level')
        menu_sort = request.data.get('menu_sort')

        menu_id = MenuModel.objects.filter(id=id).first()
        if not menu_id:
            return Response({
                'code':400,
                'msg':'菜单中不存在此目录'
            })


        MenuModel.objects.filter(id=id).update(menu_name=menu_name,menu_way=menu_way,menu_logo=menu_logo,menu_level=menu_level,menu_sort=menu_sort)

        return Response({
            'code':200,
            'msg':'菜单修改成功'
        })

# 登陆日志查询，增加
class LoginLogAPIView(APIView):
    @login
    def get(self,request):
        """
        user_id
        account
        login_equip
        login_time
        login_ip

        """
        uid = request.uid
        user = UserModel.objects.get(id=uid)
        if user.role_id_id != 2:
            user_log = LoginLogModel.objects.filter(user_id=uid)
            temp = []
            for i in user_log:
                temp.append({
                    'id':i.id,
                    'username':i.user_id.username,
                    'account':i.account,
                    'login_equip':i.login_equip,
                    'login_time':i.login_time,
                    'login_ip':i.login_ip
                })
            return Response({
                'code':200,
                'msg':'获取个人登陆日志成功',
                'user_log':temp
            })

        login_log = LoginLogModel.objects.all()
        temp = []
        for i in login_log:
            temp.append({
                'id':i.id,
                'username':i.user_id.username,
                'login_equip':i.login_equip,
                'login_time':i.login_time,
                'login_ip':i.login_ip
            })
        return Response({
            'code':200,
            'msg':'登录日志获取成功',
            'login_log':temp
        })

    @login
    def post(self,request):
        """
        user_id
        login_equip
        login_time
        login_ip

        """
        uid = request.uid
        login_equip = request.data.get('login_equip')
        login_ip = request.data.get('login_ip')
        if not all([login_equip,login_ip]):
            return Response({
                'code':400,
                'msg':'录入信息不完整'
            })
        LoginLogModel.objects.create(user_id=uid,login_equip=login_equip,login_ip=login_ip)
        return Response({
            'code':200,
            'msg':'登陆日志添加成功'
        })

# 操作日志查询，添加
class ActLogAPIView(APIView):
    @login
    def get(self,request):
        """
        actor_id
        act_thing
        act_time

        """
        uid = request.uid
        user = UserModel.objects.get(id=uid)
        if user.role_id_id != 2:
            user_log = ActLogModel.objects.filter(actor_id=uid)
            temp = []
            for i in user_log:
                temp.append({
                    'id': i.id,
                    'username': i.actor_id.username,
                    'act_thing': i.act_thing,
                    'act_time': i.act_time
                })
            return Response({
                'code': 200,
                'msg': '获取个人操作日志成功',
                'user_log': temp
            })

        act_log = ActLogModel.objects.all()
        temp = []
        for i in act_log:
            temp.append({
                'id':i.id,
                'actor':i.actor_id.username,
                'act_thing':i.act_thing,
                'act_time':i.act_time
            })
        return Response({
            'code':200,
            'msg':'操作日志获取成功'
        })

    @login
    def post(self,request):
        """
        actor_id
        act_thing
        act_time

        """
        uid = request.uid
        act_thing = request.data.get('act_thing')
        if not act_thing:
            return Response({
                'code':400,
                'msg':'必须加入用户的操作行为'
            })
        ActLogModel.objects.create(actor_id=uid,act_thing=act_thing)
        return Response({
            'code':200,
            'msg':'用户操作日志添加成功'
        })

# 工资条
class SalaryAPIView(APIView):
    def get(self,request):
        saraly = SalaryModel.objects.all()
        temp = []
        for item in saraly:
            temp.append({
                'id':item.id,
                'username':item.name,
                'atten':item.atten,
                'absent':item.absent,
                'base_pay': item.base_pay,
                'post_pay': item.post_pay,
            })
        return Response({
            'code':200,
            'msg':"获取成功",
            'data':temp
        })

    @login
    def post(self,request):
        user_id = request.user_id
        if user_id != 1:
            return Response({
                'code': 400,
                'msg': '对不起，您没有该权限'
            })
        name = request.data.get('name')
        atten = request.data.get('atten')
        absent = request.data.get('absent')
        base_pay = request.data.get('base_pay')
        post_pay = request.data.get('post_pay')
        if not all([name,atten,absent,base_pay,post_pay]):
            return Response({
                'code':400,
                'msg':"参数错误"
            })
        s = SalaryModel.objects.filter(name=name).first()
        if not s:
            SalaryModel.objects.create(name=name,atten=atten,absent=absent,base_pay=base_pay,post_pay=post_pay)
            return Response({
                'code':201,
                'msg':"添加成功"
            })
        else:
            return Response({
                'code':400,
                'msg':'已有用户信息'
            })


# 材料上传
class StuffAPIView(APIView):
    @login
    def get(self,request):
        """
        stuff
        stuff_addr
        upper
        up_time
        """
        stuff_all = StuffModel.objects.all()
        temp = []
        for i in stuff_all:
            temp.append({
                'id':i.id,
                'stuff':i.stuff,
                'stuff_addr':i.stuff_addr,
                'upper':i.upper.username,
                'up_time':i.up_time
            })

        return Response({
            'code':200,
            'msg':'材料信息获取成功'
        })

    @login
    def post(self,request):
        """
        stuff
        stuff_addr
        upper
        up_time
        """
        stuff = request.data.get('stuff')
        stuff_addr = request.data.get('stuff_addr')
        upper = request.data.get('upper')
        up_time = request.data.get('up_time')
        if not all([stuff,stuff_addr,upper,up_time]):
            return Response({
                'code':400,
                'msg':'材料输入信息不完整'
            })
        StuffModel.objects.create(stuff=stuff,stuff_addr=stuff_addr,upper=upper)
        return Response({
            'code':200,
            'msg':'材料添加成功'
        })

# 材料修改，删除
class StuffView(APIView):
    @login
    def delete(self,request,id):
        uid = request.uid
        user = UserModel.objects.get(id=uid)
        if user.role_id_id != 2:
            return Response({
                'code': 400,
                'msg': '抱歉，您没有权限'
            })
        StuffModel.objects.get(id=id).delete()
        return Response({
            'code':200,
            'msg':'材料删除成功'
        })

    @login
    def put(self,request,id):
        """
        stuff
        stuff_addr
        upper
        up_time
        """

        uid = request.uid
        user = UserModel.objects.get(id=uid)
        if user.role_id_id != 2:
            return Response({
                'code': 400,
                'msg': '抱歉，您没有权限'
            })

        stuff = request.data.get('stuff')
        stuff_addr = request.data.get('stuff_addr')
        upper = request.data.get('upper')
        if not all([stuff,stuff_addr,upper]):
            return Response({
                'code':400,
                'msg':'录入信息不完整'
            })
        StuffModel.objects.filter(id=id).update(stuff=stuff,stuff_addr=stuff_addr)
        return Response({
            'code':200,
            'msg':'材料修改成功'
        })


# 文件上传（工资条）
class UploadSalaryAPIView(APIView):
    # 添加工资条
    def post(self, request):
        excel = request.FILES.get('file')
        row_name = excel.name.split(".")[1]
        if row_name != "xlsx" and row_name != "elsx":
            return Response({
                "code":400,
                "msg":"文件格式错误"
            })
        md5_name = row_name + "." + excel.name.split(".")[1]
        print('>>>>>>',row_name)
        with open('./excel/' + md5_name, 'wb')as f:
            for chunk in excel.chunks():
                f.write(chunk)

        # 打开文件
        file_path = './excel/' + md5_name
        data = xlrd2.open_workbook(file_path)

        names = data.sheet_names()

        # 选择工作表
        sheet = data.sheet_by_name(names[0])
        print('<>>>>>>>',sheet)

        # 有多少行
        rows = sheet.nrows
        print(rows)
        list1 = []

        for i in range(1, rows):
            shuju = sheet.row_slice(i)
            print('>>>>>>>>>', shuju)
            for x in shuju:
                data = str(x).split(':')[-1]
                list1.append(data)
                print('>>>>>>>>>>>>>><<<<<<<<<<<<<<', data)

        a = 0
        b = 1
        c = 2
        d = 3
        e = 4
        print(list1)
        for t in range(1, rows):
            try:
                # ids = EmployeeModel.objects.filter(name=name).first()
                # print(">>>>>>>>>>>>>>>>>>>>>>213124312423432423432>",ids)
                SalaryModel.objects.create(
                    name=list1[a].split("'")[1],
                    absent=str(list1[b].split('.')[0]),
                    atten=str(list1[c].split('.')[0]),
                    base_pay=int(list1[d].split('.')[0]),
                    post_pay=int(list1[e].split('.')[0]),
                )
                print("------------------", list1[a].split("'")[1])
                print("------------------", str(list1[b].split('.')[0]))
                print("-------------------", str(list1[c].split('.')[0]))
                print("--------------------", int(list1[d].split('.')[0]))
                print("--------------------", int(list1[e].split('.')[0]))

            except Exception as e:
                print('<><sadasd错误', e)

                return Response({
                    'code': 400,
                    'msg': '请检查表格格式是否正确'
                })
            a += 5
            b += 5
            c += 5
            d += 5
            e += 5
        return Response({
            'code': 200,
            'msg': '上传成功'
        })


class AddEmailView(APIView):
    # 查看邮箱信息
    @login
    def get(self,request):
        user_id = request.uid
        kok = EmailModel.objects.filter(employee_id=user_id).all()
        data = []
        for i in kok:
            d = {
                "id":i.id,
                "employee":i.employee.username,
                "email_receipt":i.email_receipt,
                "email_data":i.email_data,
                "title":i.title,
                "url":i.url
            }
            data.append(d)
        return Response({
            "code":200,
            "msg":"成功",
            "data":data
        })

    # 发送邮件
    @login
    def post(self,request):
        uid = request.uid
        aa = UserModel.objects.get(id=uid)
        sender = aa.mail
        # 收件人邮箱
        email_receipt = request.data.get("email_receipt")
        # 邮箱内容
        email_data = request.data.get("email_data")
        # 标题
        subject = request.data.get("title")
        # 地址
        url = request.data.get("url")

        if not all([email_receipt,email_data,subject,url]):
            return Response({
                "code":400,
                "msg":"数据不能为空"
            })


        mail_pass = 'yqkgzkpgcxzfbjaj'
        message = MIMEText(email_data, 'plain', 'utf-8')

        # 添加Header信息，From，To，Subject分别为发送者信息，接收者消息和邮件主题
        message['From'] = Header(sender, 'utf-8')
        message['To'] = Header(email_receipt, 'utf-8')
        message['Subject'] = Header(subject, 'utf-8')

        try:
            # smtp.xxx.com为邮箱服务类型，25为STMP的端口
            smtpObj = smtplib.SMTP('smtp.qq.com', 25)  # smtp.xxx.com为邮箱服务类型，25为STMP
            # smtpObj = smtplib.SMTP_SSL('smtp.xxx.com', 'xxx邮件服务的端口号')

            smtpObj.login(sender, mail_pass)  # 登录
            smtpObj.sendmail(sender, email_receipt, message.as_string())  # 发送
            EmailModel.objects.create(employee_id=uid,email_receipt=email_receipt,email_data=email_data,title=subject,url=url)
            return Response({
                "code":200,
                "msg":"发送成功"
            })
        except smtplib.SMTPException:
            return Response({
                "code":400,
                "msg":"发送失败"
            })

class EmailInfoView(APIView):
    # 获取单条邮箱信息
    @login
    def get(self,request,id):
        kok = EmailModel.objects.get(id=id)
        if not kok:
            return Response({
                "code":400,
                "msg":"数据不存在"
            })
        return Response({
            "code":200,
            "msg":"成功",
            "data":{
                "id":kok.id,
                "employee":kok.employee_id,
                "email_receipt":kok.email_receipt,
                "email_data":kok.email_data,
                "title":kok.title,
                "url":kok.url
            }
        })

    # 删除邮箱信息
    @login
    def delete(self,request,id):
        kok = EmailModel.objects.get(id=id)
        if not kok:
            return Response({
                "code": 400,
                "msg": "数据不存在"
            })
        kok.delete()

        return Response({
            "code":200,
            "msg":"删除成功"
        })

    # 修改邮箱信息
    @login
    def put(self,request,id):
        email_receipt = request.data.get("email_receipt")
        email_data = request.data.get("email_data")
        title = request.data.get("title")
        url = request.data.get("url")
        if not all([email_data,email_receipt,title,url]):
            return Response({
                "code":400,
                "msg":"数据不能为空"
            })

        kok = EmailModel.objects.get(id=id)
        if not kok:
            return Response({
                "code": 400,
                "msg": "数据不存在"
            })
        if email_receipt and email_receipt != kok.email_receipt:
            kok.email_receipt = email_receipt
        if email_data and email_data != kok.email_data:
            kok.email_data = email_data
        if title and title != kok.title:
            kok.title = title
        if url and url != kok.url:
            kok.url = url

        kok.save()

        return Response({
            "code":200,
            "msg":"修改成功"
        })


class AddCopyView(APIView):
    # 查看抄送人
    @login
    def get(self,request):
        user_id = request.uid
        kok = EmailModel.objects.filter(employee_id=user_id).first()
        data = CopyModel.objects.filter(email_id=kok.id)
        pop = []
        for i in data:
            d = {
                "id":i.id,
                "email":user_id,
                "email_copy" : i.email_copy
            }
            pop.append(d)
        return Response({
            "code":200,
            "msg":"成功",
            "data":pop
        })

    # 添加抄送人
    @login
    def post(self,request):
        user_id = request.uid
        email_copy = request.data.get("email_copy")
        if not all([user_id,email_copy]):
            return Response({
                "code":400,
                'msg':"数据不能为空"
            })
        aaa = EmailModel.objects.filter(employee_id=user_id).first()
        CopyModel.objects.create(email_id=aaa.id,email_copy=email_copy)

        return Response({
            "code":200,
            "msg":"添加成功"
        })

class CopyInfoView(APIView):
    # 获取单条抄送人
    @login
    def get(self,request,id):
        kok = CopyModel.objects.get(id=id)
        if not kok:
            return Response({
                "code":400,
                "msg":"数据不存在"
            })
        return Response({
            "code":200,
            "msg":"成功",
            "data":{
                "id":kok.id,
                "email":kok.email.employee.username,
                "email_copy":kok.email_copy
            }
        })

    # 删除抄送人
    @login
    def delete(self,request,id):
        kok = CopyModel.objects.get(id=id)
        if not kok:
            return Response({
                "code": 400,
                "msg": "数据不存在"
            })
        kok.delete()

        return Response({
            "code":200,
            "msg":"删除成功"
        })

    # 修改抄送人
    @login
    def put(self,request,id):
        email_copy = request.data.get("email_copy")
        if not email_copy:
            return Response({
                "code":400,
                "msg":"数据不能为空"
            })
        kok = CopyModel.objects.get(id=id)
        if not kok:
            return Response({
                "code": 400,
                "msg": "数据不存在"
            })
        if email_copy and email_copy != kok.email_copy:
            kok.email_copy = email_copy
        kok.save()

        return Response({
            "code":200,
            "msg":"修改成功"
        })
